<?php

class Rzd_Validate_DatesComparison extends Zend_Validate_Abstract
{
    protected  $_comparisonDateFieldName = null;
    protected  $_operation = null;
    protected  $_comparisonWithCurrentDate = null;

    const DATE_SHOULD_BE_LESS = 'dateShouldBeLess';
    const DATE_SHOULD_BE_GREATER = 'dateShouldBeGreater';
    const DATE_SHOULD_BE_EQUAL = 'dateEqual';
    const DATE_SHOULD_BE_LESS_OR_EQUAL = 'dateLessOrEqual';
    const DATE_SHOULD_BE_GREATER_OR_EQUAL = 'dateGreedOrEuqal';

    protected $_messageTemplates = array(
        self::DATE_SHOULD_BE_LESS => "This date should be before than %value%",
        self::DATE_SHOULD_BE_GREATER => "This date should be greater than %value%",
        self::DATE_SHOULD_BE_EQUAL => "This date should be equal than %value%",
        self::DATE_SHOULD_BE_LESS_OR_EQUAL => "This date should be less or equal %value%",
        self::DATE_SHOULD_BE_GREATER_OR_EQUAL => "This date should be after %value%"
    );

    public function __construct($validateOptions)
    {
        $this->_comparisonDateFieldName = isset($validateOptions['comparison_field_name']) ? $validateOptions['comparison_field_name'] : null;
        $this->_operation = isset($validateOptions['operation']) ? $validateOptions['operation'] : null;
        $this->_comparisonWithCurrentDate = isset($validateOptions['compration_with_cur_date']) ? $validateOptions['operation'] : null;
    }

    public function isValid($value, $context=null)
    {
        if($this->_comparisonWithCurrentDate) {
            $comparisonValue = date('Y-m-d', time());
        } else {
            $comparisonValue = $context[$this->_comparisonDateFieldName];
        }

        $this->_setValue($comparisonValue);

        switch ($this->_operation) {
            case self::DATE_SHOULD_BE_LESS :
                if(!($value < $comparisonValue)) {
                    $this->_error(self::DATE_SHOULD_BE_LESS);
                    return false;
                }
            break;
            case self::DATE_SHOULD_BE_GREATER:
                if(!($value > $comparisonValue)) {
                    $this->_error(self::DATE_SHOULD_BE_GREATER);
                    return false;
                }
            break;
            case self::DATE_SHOULD_BE_EQUAL :
                if(!($value == $comparisonValue)) {
                    $this->_error(self::DATE_SHOULD_BE_EQUAL);
                    return false;
                }
            break;
            case self::DATE_SHOULD_BE_LESS_OR_EQUAL :
                if(!($value <= $comparisonValue)) {
                    $this->_error(self::DATE_SHOULD_BE_LESS_OR_EQUAL);
                    return false;
                }
            break;
            case self::DATE_SHOULD_BE_GREATER_OR_EQUAL :
                if(!($value >= $comparisonValue)) {
                    $this->_error(self::DATE_SHOULD_BE_GREATER_OR_EQUAL);
                    return false;
                }
            break;
        }

        return true;
    }
}